#include "aduc812.h"
#include "interrupt.h"
#include "rs232.h"
#include "fifo.h"
#include "led.h"

struct FIFO T_FIFO;
struct FIFO R_FIFO;

void _int_uart() __interrupt(1) {
	char tmp;
	if (TI && get(&T_FIFO, &tmp)) { SBUF = tmp; TI = 0; }
	if (RI) { put(&R_FIFO, SBUF); RI = 0; }
}

void init_rs232() {
	new_fifo(&T_FIFO);
	new_fifo(&R_FIFO);
	int_vector(0x2023, (void *) _int_uart);
	TH1 = TL1 = s9600;						// 	set speed
	TMOD = (TMOD & 0x0F) | 0x20;	// 	timer 8bit with reoad
	SCON = 0x50; 									// 	uart 8bit with variable speed
	PCON &= 0x7F;									// 	double baud rate control 0
	ET1 = 0;											// 	disable interrupt from timer 1
	TR1 = 1;											// 	start timer 1
	ES = 1;												// 	enable interrupt from uart
	EA = 1;												// 	enable interrupt
	TI = 1;												// 	enable transfer
}

char write_rs232(char value) {
	char flag;
	ES = 0;
	flag = put(&T_FIFO, value);
	ES = 1;
	return flag;
}

char read_rs232(char * value) {
	char flag;
	ES = 0;
	flag = get(&R_FIFO, value);
	ES = 1;
	return flag;
}

void println_rs232(char * s) {
	char tmp;
	while (1) {
		tmp = *s++;
		while(!write_rs232(tmp));
		if (!tmp || tmp == '\n') break;
	}
}

void scanln_rs232(char * s) {
	char tmp;
	while (1) {
		while(!read_rs232(&tmp));
		while(!write_rs232(tmp));
		*s++ = tmp;
		if (!tmp || tmp == '\n') break;
	}
}
